import Router from 'koa-router'
import nodeMailer from 'nodemailer'
import util from '../util'
import axios from '../util/axios'
import Passport from '../util/passport'

import { getRedisConnect } from '../db/init'
import serverConf from '../../config/server'
import UserModel from '../db/models/User'

const router = new Router({ prefix: '/user' })

const store = getRedisConnect().client

router.post('/verify', async ctx => {
  ctx.body = { code: -1, msg: '' }
  const { username, email } = ctx.request.body

  const _expire = await store.hget(`nodemailer:${username}`, 'expire')
  if (new Date().getTime() - _expire < 0) return (ctx.body.msg = '验证码请求过于频繁，请稍后重试')

  const code = util.getCode(), expire = util.getExpire()

  const mailInfo = {
    from: `认证邮件 <${serverConf.smtp.user}>`,
    to: email,
    subject: `《 美团注册码 》`,
    html: `您的邀请码是 ${code}`
  }

  const transport = nodeMailer.createTransport({
    service: 'qq',
    auth: {
      user: serverConf.smtp.user,
      pass: serverConf.smtp.pass
    }
  })
  await transport.sendMail(mailInfo, error => {
    if (error) {
      return console.log('send mail error ' + error)
    }
    store.hmset(`nodemailer:${username}`, 'code', code, 'expire', expire, 'email', email)
  })
  ctx.body = {
    code: 0,
    msg: '验证码已发送，请在三分钟内验证'
  }
})

router.post('/signup', async ctx => {
  ctx.body = { code: -1, msg: '' }

  const { username, password, email, code } = ctx.request.body

  if (!code) return (ctx.body.msg = '请输入验证码')

  const _code = await store.hget(`nodemailer:${username}`, 'code')
  if (_code !== code) return (ctx.body.msg = '请输入正确验证码')

  const expire = await store.hget(`nodemailer:${username}`, 'expire')
  if (new Date().getTime() - expire > 0) return (ctx.body.msg = '验证码超时，请重新获取')

  const dbUser = await UserModel.findOne({ username })
  if (dbUser) return (ctx.body.msg = '用户名已存在')

  const saveRes = await UserModel.create({ username, password, email })
  if (!saveRes) return (ctx.body.msg = '注册失败')

  const loginRes = await axios.post('/user/signin', { username, password })
  if (!loginRes.data) return (ctx.body.msg = '注册失败 signin')

  ctx.body = {
    code: 0,
    msg: '注册成功',
    user: loginRes.data.user
  }
})

router.post('/signin', async (ctx, next) => {
  ctx.body = { code: -1, msg: '' }
  return Passport.authenticate('local', (err, user, info, status) => {
    if (err) return (ctx.body.mag = err)
    if (!user) return (ctx.body.msg = info)
    ctx.body = {
      code: 0,
      user
    }
    return ctx.login(user)
  })(ctx, next)
})

router.get('/signout', async ctx => {
  await ctx.logout()
  ctx.body = {
    code: ctx.isAuthenticated() ? -1 : 0
  }
})

router.get('/getUserInfo', async ctx => {
  if (ctx.isAuthenticated()) {
    const { username, email } = ctx.session.passport.user
    ctx.body = {
      code: 0,
      username,
      email
    }
  } else {
    ctx.body = {
      code: -1,
      username: '',
      email: ''
    }
  }
})

export default router
